package com.cc.data_explore.gui.tab;

import atlantafx.base.theme.Styles;
import com.cc.data_explore.logic.mybatis.DbHelper;
import com.cc.data_explore.logic.mybatis.mapper.main.BaseDbMapper;
import com.cc.data_explore.logic.mybatis.model.BaseDb;
import de.saxsys.mvvmfx.FxmlView;
import de.saxsys.mvvmfx.InjectViewModel;
import de.saxsys.mvvmfx.MvvmFX;
import javafx.beans.binding.Bindings;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.layout.HBox;
import javafx.util.Callback;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.dromara.hutool.core.date.DateUtil;
import org.kordamp.ikonli.javafx.FontIcon;
import org.kordamp.ikonli.materialdesign2.MaterialDesignD;
import org.kordamp.ikonli.materialdesign2.MaterialDesignF;

import java.time.LocalDateTime;

import static atlantafx.base.theme.Styles.FLAT;

/**
 * WorkspaceView
 *
 * @author aa
 * @version 1.0
 * @since 2025/4/2
 */
public class WorkspaceView implements FxmlView<WorkspaceViewModel> {
    @FXML
    public TextField searchText;
    @FXML
    public Button searchBtn;
    @FXML
    public TableView<BaseDb> dsTableView;
    @FXML
    public TableColumn<BaseDb, String> nameTableColumn;
    @FXML
    public TableColumn<BaseDb, LocalDateTime> createDateTableColumn;
    @FXML
    public TableColumn<BaseDb, String> optColumn;

    @InjectViewModel
    private WorkspaceViewModel workspaceViewModel;

    @FXML
    public void initialize() {

        searchText.textProperty().bindBidirectional(workspaceViewModel.searchTextProperty());
        nameTableColumn.setCellValueFactory(new PropertyValueFactory<>("dbName"));
        nameTableColumn.setCellFactory(TextFieldTableCell.forTableColumn());
        createDateTableColumn.setCellValueFactory(new PropertyValueFactory<>("createTime"));
        createDateTableColumn.setCellFactory(call -> new TableCell<>() {
            @Override
            protected void updateItem(LocalDateTime item, boolean empty) {
                super.updateItem(item, empty);
                if (empty) {
                    setText(null);
                } else {
                    if (item != null) {
                        this.setText(DateUtil.format(item, "yyyy-MM-dd HH:mm:ss"));
                    }
                }
            }
        });
        Bindings.bindContent(dsTableView.getItems(), workspaceViewModel.dbs());
        nameTableColumn.setOnEditCommit(event -> {
            BaseDb rowValue = event.getRowValue();
            String newValue = event.getNewValue();
            SqlSessionFactory sqlSessionFactory = DbHelper.getInstance().getSqlSessionFactory(DbHelper.MAIN_DB_NAME);
            try (SqlSession sqlSession = sqlSessionFactory.openSession(true)) {
                BaseDbMapper mapper = sqlSession.getMapper(BaseDbMapper.class);
                rowValue.setDbName(newValue);
                mapper.updateById(rowValue);
            }
            rowValue.setDbName(newValue);
        });
        optColumn.setCellFactory(new Callback<>() {
            @Override
            public TableCell<BaseDb, String> call(TableColumn<BaseDb, String> param) {
                return new TableCell<>() {
                    @Override
                    protected void updateItem(String item, boolean empty) {
                        super.updateItem(item, empty);
                        if (empty && item == null) {
                            setGraphic(null);
                        } else {
                            HBox hBox = new HBox();
                            hBox.setSpacing(10);
                            Button openBtn = new Button("打开");
                            openBtn.setGraphic(FontIcon.of(MaterialDesignF.FOLDER_PLUS_OUTLINE));
                            openBtn.getStyleClass().addAll(Styles.FLAT, Styles.ACCENT);
                            openBtn.setOnAction(event -> {
                                BaseDb baseDb = getTableView().getItems().get(getIndex());
                                MvvmFX.getNotificationCenter().publish("WORKSPACE_CREATE_TAB", baseDb.getDbFile());
                            });
                            Button delBtn = new Button("删除");
                            delBtn.setGraphic(FontIcon.of(MaterialDesignD.DELETE_FOREVER));
                            delBtn.getStyleClass().addAll(FLAT, Styles.DANGER);
                            delBtn.setOnAction(event -> {
                                BaseDb baseDb = getTableView().getItems().get(getIndex());
                                workspaceViewModel.delBaseDb(baseDb);
                            });
                            hBox.getChildren().addAll(openBtn, delBtn);
                            setGraphic(hBox);
                        }
                    }
                };
            }
        });
        MvvmFX.getNotificationCenter().subscribe("REFRESH_WORKSPACE", (k, v) -> workspaceViewModel.loadBaseDb());
    }

    public void searchFun(ActionEvent actionEvent) {
        workspaceViewModel.loadBaseDb();
    }
}
